﻿Imports System.Net
Imports System.IO
Imports System.ComponentModel

Public Class downloadingimage
    Shared cilent As New WebClient
    Shared imgtype As String
    Shared savepath As String
    Shared ttd As String
    ''' <summary>
    ''' The path on the computer where you want the image to be saved to.
    ''' </summary>
    ''' <param name="PathToSave"></param>
    ''' The URL of the image you want to download.
    ''' <param name="ImageURL"></param>
    Public Shared Sub StartDownload(PathToSave As String, ImageURL As String, Optional TextToDisplay As String = "The image download was done.")
        Try

            imgtype = ImageURL.Substring(ImageURL.Length - 4, 4)
            Directory.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData)
            savepath = PathToSave
            ttd = TextToDisplay
            If System.IO.File.Exists(PathToSave) Then
                AddHandler cilent.DownloadFileCompleted, AddressOf DownloadFileCallback1
                IO.File.Delete(PathToSave)
                cilent.DownloadFileAsync(New Uri(ImageURL), PathToSave)


            Else

                AddHandler cilent.DownloadFileCompleted, AddressOf DownloadFileCallback1
                cilent.DownloadFileAsync(New Uri(ImageURL), PathToSave)

            End If
        Catch ex As Exception
            Throw New Exception("Error downloading image. Please check the URL to be valid.")
        End Try

    End Sub

    Shared Sub DownloadFileCallback1(sender As Object, e As AsyncCompletedEventArgs)
        MsgBox(ttd, MsgBoxStyle.Information)
    End Sub
End Class
